package com.yun.csv2db.writer;

import com.yun.csv2db.entity.Teacher;
import com.yun.csv2db.entity.enums.SexEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class TeacherItemWriter implements ItemWriter<Teacher> {
    private static final String GET_TEACHER = "select * from TEACHER where id = ?";
    private static final String INSERT_TEACHER = "insert into TEACHER (id,name,sex,birth_date,home_address,school,working_years,update_time,create_time) values (?,?,?,?,?,?,?,?,?)";
    private static final String UPDATE_TEACHER = "update TEACHER set name = ?, sex = ?, birth_date = ?, home_address = ?, school = ?, working_years = ?, update_time = ? where id = ?";
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void write(List<? extends Teacher> teachers) throws Exception {
        for (Teacher teacher : teachers) {
            //查看是否有对应的数据
            List<Teacher> teacherList = jdbcTemplate.query(GET_TEACHER, new Object[]{teacher.getId()}, new RowMapper<Teacher>() {
                public Teacher mapRow(ResultSet resultSet, int rowNum) throws SQLException {
                    Teacher s = new Teacher();
                    s.setId(resultSet.getInt("id"));
                    s.setName(resultSet.getString("name"));
                    s.setSex(SexEnum.getEnumFromString(resultSet.getString("sex")));
                    s.setBirthDate(resultSet.getString("birth_date"));
                    s.setHomeAddress(resultSet.getString("home_address"));
                    s.setSchool(resultSet.getString("school"));
                    s.setWorkingYears(resultSet.getInt("working_years"));
                    s.setUpdateTime();
                    return s;
                }
            });
            //有数据更新
            if (teacherList.size() > 0) {
                jdbcTemplate.update(UPDATE_TEACHER, teacher.getName(), teacher.getSex().name(), teacher.getBirthDate(), teacher.getHomeAddress(),
                        teacher.getSchool(), teacher.getWorkingYears(), teacher.getUpdateTime(), teacher.getId());
                logger.info("Update successful.");
            }
            //没有数据就插入
            else {
                jdbcTemplate.update(INSERT_TEACHER, teacher.getId(), teacher.getName(), teacher.getSex().name(), teacher.getBirthDate(),
                        teacher.getHomeAddress(), teacher.getSchool(), teacher.getWorkingYears(), teacher.getUpdateTime(), teacher.getCreateTime());
                logger.info("Insert successful.");
            }

        }
    }
}
